<?php
/*******************************************************************************
itemManager.class.php

Created by Jason White (jbwhite@emory.edu)
Modified by NCSU Libraries, NC State University. Modifications by Karl Doerr and Troy Hurteau (libraries.opensource@ncsu.edu).

This file is part of NCSU's distribution of ReservesDirect. This version has not been downloaded from Emory University
or the original developers of ReservesDirect. Neither Emory University nor the original developers of ReservesDirect have authorized
or otherwise endorsed or approved this distribution of the software.

Copyright (c) 2004-2006 Emory University, Atlanta, Georgia.

Licensed under the NCSU ReservesDirect License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. You may obtain a copy of the full License at
 http://www.lib.ncsu.edu/it/opensource/

ReservesDirect is distributed in the hope that it will be useful,
but is distributed "AS IS" and WITHOUT ANY WARRANTY, without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE, and without any warranty as to non-infringement of any third
party's rights. See the License for the specific language governing permissions and limitations under the License.

The original version of ReservesDirect is located at:
http://www.reservesdirect.org/

This version of ReservesDirect, distributed by NCSU, is located at:
http://code.google.com/p/reservesdirect-ncsu/

*******************************************************************************/
//require_once(APPLICATION_PATH . '/common.inc.php');
require_once(APPLICATION_PATH . '/displayers/itemDisplayer.class.php');
require_once(APPLICATION_PATH . '/managers/classManager.class.php'); //#TODO deprecate?
require_once(APPLICATION_PATH . '/managers/copyrightManager.class.php'); //#TODO deprecate?
require_once(APPLICATION_PATH . '/managers/reservesManager.class.php'); //#TODO deprecate?
require_once(APPLICATION_PATH . '/classes/note.class.php');
require_once(APPLICATION_PATH . '/displayers/requestDisplayer.class.php');
require_once(APPLICATION_PATH . '/lib/Rd/Library.php');

require_once(APPLICATION_PATH . '/lib/Rd/Synchronizer/ItemPhysicalCopies.php'); //#TODO is this used here?
require_once(APPLICATION_PATH . '/lib/Validator/Url.php');

class itemManager extends Rd_Manager_Base
{
	public $user;
	public $displayClass;
	public $displayFunction;
	public $argList;

/*	function display()
	{
		$args = array();
		foreach($this->argList as $index=>$value){
			$args[$index] =& $this->argList[$index];
		}
		if (is_callable(array($this->displayClass, $this->displayFunction))){
			$this->_displayer = new $this->displayClass();
			call_user_func_array(array($this->_displayer, $this->displayFunction), $args);
		}
	}
*/
	function __construct($cmd, $request, $user) //#TODO deprecate $user, and support the $iwth mechanism
	{
		global $ci; //ugh. really?
		$u = Rd_Registry::get('root:userInterface');
		$this->displayClass = 'itemDisplayer';
		$this->with('960css');
		switch ($cmd)
		{		
			case 'duplicateReserve':	//duplicates reserve AND item
				if(empty($request['reserveID']))
					break;	//error, no reserveID set
								
				//get the source reserve
				$srcReserve = new reserve($request['reserveID']);				
				//duplicate it
				$dupReserveID = $srcReserve->duplicateReserve();				
				
				//set up some vars
				
				$selected_instr = $request['selected_instr'];	//remember instructor
				
				$request = array();	//clear current request
				
				$request['reserveID'] = $dupReserveID;	//set up new reserveID
				$request['dubReserve'] = true;	//set flag, to let editItem handler know this is a dupe
				$request['selected_instr'] = $selected_instr;	//set instructor
				$this->_editItemAction($request);
				break;

			case 'editHeading':
				$this->_setTab(($u->getRole() >= Account_Rd::LEVEL_STAFF) ? 'manageClasses' : 'addReserve');
				$this->_setLocation('edit heading');
				Rd_Help::setDefaultArticleId(35);
				
				$headingID = !empty($request['headingID']) ? $request['headingID'] : null;
				$heading = new reserve($headingID);
				
				$this->displayFunction = 'displayEditHeadingScreen';
				$this->setModel(array(
					'ci' => $request['ci'],
					'heading' => $heading
				));
				break;
			
			case 'processHeading':
				$this->_setTab('myReserves');
				$this->_setLocation('edit heading');
				Rd_Help::setDefaultArticleId(35);
				$tempReserveId = "";

				$ci = new courseInstance($request['ci']);
				$headingText = $request['heading'];
				$headingID = $request['headingID'];
				$activation_date = isset($request['reserve_activation_date']) ? $request['reserve_activation_date'] : $ci->activationDate;
				$expiration_date = isset($request['reserve_expiration_date']) ? $request['reserve_expiration_date'] : $ci->expirationDate;
				$aciton = "";
				
				//Set activation Date
				//Set expiration Date
				
				if(empty($headingID)) {	//need to create a new item
					if ($headingText) {
						$heading = new item();				
						$heading->createNewItem();
						$heading->makeHeading();
						$reserve = new reserve();
						$reserve->createNewReserve($ci->getCourseInstanceID(), $heading->itemID);
						$reserve->setStatus(Rd_Request_Status::getActiveStatusId());
						$reserve->setActivationDate($activation_date);
						$reserve->setExpirationDate($expiration_date);
						$reserve->insertIntoSortOrder($ci->getCourseInstanceID(), $headingText, 'zzzzz');	//zzzz will put the heading last if author-sorted
						$tempReserveId = $reserve->getReserveID();
						$headingID = $heading->getItemID();
						$action = courseInstanceAudit::EVENT_ADD;
						
					}
				} else {
					$heading = new item($headingID);
					$action = courseInstanceAudit::EVENT_EDIT;
				}
				$headingReserveID = (isset($request['reserveID']) && $request['reserveID'] != "") ? $request['reserveID'] : $tempReserveId;
				
				
				if ($headingText) {
					$heading->setTitle($headingText);
				}
				if(isset($request['reserve_activation_date']) || isset($request['reserve_expiration_date'])){	
					$reserve_heading = new reserve($headingReserveID);
					if(isset($request['reserve_activation_date'])){
						$reserve_heading->setActivationDate($activation_date);
					}
					if(isset($request['reserve_expiration_date'])){
						$reserve_heading->setExpirationDate($expiration_date);
					}	
				}
				//notes
				if(!empty($request['notes'])) {
					foreach($request['notes'] as $note_id=>$note_text) {
						if(!empty($note_id)) {
							$note = new note($note_id);
							$note->setText($note_text);
						}
					}
				}
				
				$cia = new courseInstanceAudit();
				//echo $action;
				$cia->logHeadingEvent($request['ci'], $headingID, $action);
				$this->displayFunction = 'displayHeadingSuccessScreen';
				$this->setModel(array('ciId' => $request['ci']));
				break;
			default: 
				parent::__construct($cmd, $request); //#TODO $with
		}	
	}
	
	public function editItemAction($request)
	{
		//switch b/n editing item or editing reserve+item
		$activeStatusId = Rd_Request_Status::getActiveStatusId();
		$reserve = NULL;
		$item = NULL;
		if(Rd_Array::keyExistsAndNotBlank('reserveID', $request)) {	//editing item+reserve
			//get reserve
			$reserve = new reserve($request['reserveID']);
			if (!$reserve || !$reserve->isInstantiated()) {
				throw new Rd_Exception_Support('The requested reserve was not found in the database.');
			}
			//get item
			$item = new reserveItem($reserve->getItemID());
			
			//init a courseInstance to show location				
			$ci = new courseInstance($reserve->getCourseInstanceID());
		} elseif(Rd_Array::keyExistsAndNotBlank('itemID', $request)) {	//editing item only
			$item = new reserveItem($request['itemID']);
		} else {	//no IDs set, error
			Rd_Status::set(400);
			throw new Exception('No Item or Reserve specified.'); 
		}
		if (!$item || !$item->isInstantiated()) {
			throw new Rd_Exception_Support('The requested item was not found in the database.');
		}			
		
		
		
		//form submitted - edit item meta
		if(!empty($request['submit_edit_item_meta'])) {
			$success = TRUE;
			//were we editing a reserve?
			if($reserve instanceof reserve) {	//set some data;
				//set status
				if (array_key_exists('reserve_status', $request)) {
					$reserve->setStatus($request['reserve_status']);
					if($request['reserve_status'] == $activeStatusId) {
						//if not empty, set activation and expiration dates
						if(!empty($request['reserve_activation_date'])) {
							$reserve->setActivationDate($request['reserve_activation_date']);
						}
						if(!empty($request['reserve_expiration_date'])) {
							$reserve->setExpirationDate($request['reserve_expiration_date']);
						}		
					}
				}
				
				//set parent heading
				if(array_key_exists('heading_select', $request)) { //!empty($_REQUEST['heading_select'])) {
					$reserve->setParent($request['heading_select'], true);
				}	
			}
			
			//if editing electronic item, manage files
			
			if(isset($request['documentType'])) {						
				if($request['documentType'] == 'DOCUMENT') {	//uploaded file?
					$file = common_storeUploaded($_FILES['userFile'], $item->getItemID());
					
					$file_loc = $file['dir'] . $file['name'] . $file['ext'];
					$item->setURL($file_loc);
					$item->setMimeTypeByFileExt($file['ext']);
					if ($item->copyrightReviewRequired())
					{
						$classes = $item->getAllCourseInstances();
						for($i=0; $i < sizeof($classes); $i++)
						{
							$classes[$i]->clearReviewed();
						}
					}
				}
				elseif($request['documentType'] == 'VIDEO'){
					$file = common_storeVideo($_FILES['userFile'], $item->getItemID(), $u, $item->getTitle());
					$item->setURL($file);
					$item->setMimeTypeByFileExt($file['ext'], true);
					if ($item->copyrightReviewRequired())
					{
						$classes = $item->getAllCourseInstances();
						for($i=0; $i < sizeof($classes); $i++)
						{
							$classes[$i]->clearReviewed();
						}
					}
				}
				
				
				elseif($request['documentType'] == 'URL') {	//link?
					if (Validator_Url::validate($request['url'])) {
						$item->setURL($request['url']);
					} else {
						$success = FALSE;
					}
				}
				//else maintaining the same link; do nothing
			}
			
			//set item data
			$item->setTitle($request['title']); //#TODO this belongs in item object
			$item->setAuthor($request['author']);
			$item->setPerformer($request['performer']);
			$item->setDocTypeIcon($request['selectedDocIcon']);
			$item->setVolumeTitle($request['volumeTitle']);
			$item->setVolumeEdition($request['volumeEdition']);
			$item->setPagesTimes($request['pagesTimes']);
			$item->setSource($request['source']);										
			$item->setISBN($request['ISBN']);
			$item->setISSN($request['ISSN']);
			$item->setOCLC($request['OCLC']);	
			if(
				Account_Rd::atLeastStaff()
				&& Rd_Array::keyExistsAndNotBlank('item_status', $request)
			){
				$item->setStatus($request['item_status']);	
			}
				
			//physical item data
			//if($item->isPhysicalItem()) {
			if (
				array_key_exists('home_library', $request)
				&& '' != trim($request['home_library'])
			) {
				$item->setHomeLibraryID($request['home_library']);
			}
				
			//physical copy data
			if($item->getPhysicalCopy()) {	//returns false if not a physical copy
				//only set these if they were part of the form
				if(isset($request['barcode'])) $item->physicalCopy->setBarcode($request['barcode']);
				if(isset($request['call_num'])) $item->physicalCopy->setCallNumber($request['call_num']);							
			}

			$oldLocalControlKey = $item->getLocalControlKey();
			if (
				array_key_exists('local_control_key', $request)
			) {
				$item->setLocalControlKey($request['local_control_key']);
				if ($oldLocalControlKey != $item->getLocalControlKey()) {
					$sync = new Rd_Synchronizer_ItemPhysicalCopies($item);
					$sync->syncAll();
				}
			}					
			//#TODO sync physical copies!
			// if($oldLocalControlKey != $localControlKey && '' != trim($localControlKey)){}
			
			//personal copies
			if(
				array_key_exists('personal_item', $request) 
				&& $request['personal_item'] == 'no'
			) {	//do not want a private owner
				$item->setPrivateUserID('null');
			}
			elseif(
				array_key_exists('personal_item', $request) 
				&& $request['personal_item'] == 'yes'
			) {	//we want a private owner
				//if we are choosing a new private owner, set it
				if( ($request['personal_item_owner']=='new') && !empty($request['selected_owner']) ) {
					$item->setprivateUserID($request['selected_owner']);
				}
				//else we are keeping old private owner, so no change necessary
			}
			
			//notes
			if(!empty($request['notes'])) {
				foreach($request['notes'] as $note_id=>$note_text) {
					if(!empty($note_id)) {
						$note = new note($note_id);
						$note->setText($note_text);
					}
				}
			}
			
			//if duplicating, show a different success screen
			if(array_key_exists('dubReserve', $request) && $request['dubReserve']) {
				//get course instance
				$ci = new courseInstance($reserve->getCourseInstanceID());
				$ci->getPrimaryCourse();

				//call requestDisplayer method
				$this->_setLocation('add an item');
				$this->displayClass = 'requestDisplayer';
				$this->displayFunction = 'addSuccessful';
				$this->argList = array($ci, $item->getItemID(), $reserve->getReserveID(), true);
			} else if (!$success) {
				$this->_setLocation('edit item');		
				Rd_Help::setDefaultArticleId(33);
				
				$this->displayFunction = 'displayEditItem';
				$this->setModel(array(
					'item' => $item,
					'reserve' => $reserve,
					'msg' => 'Please correct the highlighted problems below to proceed.',
					'request' => $request
				));
			} else {
				//get courseinstance id, if editing reserve
				$ci_id = ($reserve instanceof reserve) ? $reserve->getCourseInstanceID() : null;
				
				// display success
				$this->displayFunction = 'displayItemSuccessScreen';
				$this->setModel(array(
					'ciId' =>$ci_id,
					'searchParam' => (
						Rd_Array::keyExistsAndNotBlank('search', $request)
						? '&amp;search=' . urlencode($request['search']) 
						: ''
					),
					'returnItemParam' => (
						array_key_exists('reserveID', $request)
						? "&amp;reserveID={$request['reserveID']}"
						: (
							array_key_exists('itemID', $request)
							? "&amp;itemID={$request['itemID']}"
							: ''
						)
					)
				));
			}
		} else if (!empty($request['submit_edit_item_copyright'])) {	//form submitted - edit item copyright
			switch($request['form_id']) {
				case 'copyright_status':
					copyrightManager::setStatus();						
				break;
				
				case 'copyright_supporting_items_delete':
					copyrightManager::deleteSupportingItem();
				break;
				
				case 'copyright_supporting_items_add':
					copyrightManager::addSupportingItem();
				break;
			}
			
			//go back to edit item copyright screen
			$this->_setTab('addReserve');
			$this->_setLocation('edit item');		
			Rd_Help::setDefaultArticleId(33);
			
			$this->displayFunction = 'displayEditItem';
			$this->setModel(array(
				'item' => $item,
				'reserve' => $reserve
			));
		} else {	//display edit page
			$this->_setTab('addReserve');
			$this->_setLocation('edit item');
			Rd_Help::setDefaultArticleId(33);
			
			$this->displayFunction = 'displayEditItem';
			$this->setModel(array(
				'item' => $item,
				'reserve' => $reserve,
				'dubArray' => array(
					'dubReserve'=>(array_key_exists('dubReserve', $request) ? $request['dubReserve'] : ''), 
					'selected_instr'=>(array_key_exists('selected_instr', $request) ? $request['selected_instr'] : '')
				),
				'searchParams' => 
					array_key_exists('search', $request) 
					? '&amp;search=' . urlencode($request['search'])
					: ''
			));
		}
		
		$tabStyles = array(
			'meta'=>'', 
			'history'=>'', 
			'copyright'=>'', 
			'status'=>'', 
			'physicalCopies' => ''
		);
		switch((array_key_exists('tab', $request) ? $request['tab'] : '')) {
			case 'history':
				$tabStyles['history'] = 'class="current"';
			break;
			case 'status':
				$tabStyles['status'] = 'class="current"';
			break;
			case 'physicalCopies':
				$tabStyles['physicalCopies'] = 'class="current"';
			break;						
			default:
				$tabStyles['meta'] = 'class="current"';
			break;
		}
		$this->addToModel('tabStyles', $tabStyles);
		if (Account_Rd::atLeastStaff() && array_key_exists('tab', $request)) {
			$this->addToModel('tab', $request['tab']);
		}
		
	}
}

